/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.security.validate2;

import cn.nkpro.elcube.platform.gen.UserAccountSecret;
import cn.nkpro.elcube.security.UserAccountService;
import cn.nkpro.elcube.security.bo.UserDetails;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 2、使用token访问系统
 * Created by bean on 2019/12/30.
 */
@Component
@Slf4j
@Order(1001)
public class NkAccessSecretKeyAuthenticationFilter extends GenericFilterBean implements AuthenticationFilterV2 {

    @Autowired
    private AuthenticationUtils authenticationUtils;
    @Autowired
    private UserAccountService accountService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {

                // 请求地址
                String url = ((HttpServletRequest) request).getRequestURI();
                // 用户名
                String appKey    = authenticationUtils.obtainParam(request, "elcube-appKey");
                // 请求时间戳，验证签名有效期
                String timestamp = authenticationUtils.obtainParam(request, "elcube-timestamp");
                // 随机字符串，避免签名重复使用来进行攻击
                String nonce     = authenticationUtils.obtainParam(request, "elcube-nonce");
                // 签名，验证密码
                String signature = authenticationUtils.obtainParam(request, "elcube-signature");

                if (StringUtils.isNoneBlank(appKey, timestamp, nonce, signature)) {
                    // 1、校验时间戳
                    AuthenticationUtils.validateTimestamp(timestamp);
                    // 2、校验随机字符串
                    authenticationUtils.checkNonce(appKey,nonce);
                    // 3、校验错误登陆次数
                    authenticationUtils.validateErrorsLogin(appKey, false, null, null);

                    UserAccountSecret accountSecret = accountService.getAccountSecretByCode("appKey", appKey);
                    if(accountSecret==null){
                        authenticationUtils.commence((HttpServletResponse)response, new BadCredentialsException("appKey不存在"));
                        return;
                    }
                    // 验证签名
                    if(!AuthenticationUtils.validateSignature(
                            url,
                            request.getParameterMap(),
                            timestamp,
                            accountSecret.getSecret(),
                            nonce,
                            signature)){
                        authenticationUtils.throwsErrorsLogin(appKey);
                        authenticationUtils.commence((HttpServletResponse)response, new BadCredentialsException("密钥验证错误"));


                        ((HttpServletResponse)response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);

                        JSONObject json = new JSONObject();
                        json.put("code", HttpServletResponse.SC_UNAUTHORIZED);
                        json.put("msg", "密钥错误");
                        json.put("url", ((HttpServletRequest)request).getRequestURI().substring(((HttpServletRequest)request).getContextPath().length()));

                        response.setCharacterEncoding("utf-8");
                        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                        PrintWriter printWriter = response.getWriter();
                        printWriter.print(json);
                        printWriter.flush();
                        printWriter.close();

                        return;
                    }

                    UserDetails details = accountService.loadUserById(accountSecret.getAccountId());
                    AuthenticationUtils.simpleValidate(details);

                    AbstractAuthenticationToken auth = new UsernamePasswordAuthenticationToken(details.getUsername(),null, details.getAuthorities());
                    auth.setDetails(details);

                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            }
        }

        filterChain.doFilter(request, response);
    }
}
